//------------------封装函数-获取数据-------------
function loadLinksInfo() {
  $.ajax({
    url: '/admin/links',
    success: function (res) {
      // console.log(res);
      /* {status: 0, message: "获取链接信息成功！", data: Array(10)}
          data: Array(10)
          0: {id: 1, linkname: "阿云", linkurl: "hm/", linkicon: "ang", linkdesc: "", …}
          1: {id: 6, linkname: "擎", linkurl: "/", linkicon: "bg", linkdesc: "火擎", …} */
      // if(res.status===0){res.data.forEach()}
      let { status, data } = res;
      if (status === 0) {
        let str = '';
        data.forEach(item => {
          str += `<tr>
          <td>${item.id}</td>
          <td><img src="http://localhost:8888/uploads/${item.linkicon}"> </td>
          <td>${item.linkname}</td>
          <td>${item.linkurl}</td>
          <td>${item.linkdesc}</td>
          <td>
              <button data-id=${item.id} class="edit layui-btn layui-btn-sm" lay-submit lay-filter="formDemo">编辑</button>
              <button data-id=${item.id} type="reset" class="del layui-btn layui-btn-sm layui-btn-danger">删除</button>
          </td>
        </tr> `
        })
        $('tbody').html(str)
      }
    }
  })
}
loadLinksInfo()
//-----------------------------删除连接-------------------
let layer = layui.layer
$('tbody').on('click', '.del', function (e) {
  let id = $(e.target).data('id')
  // console.log(id);
  layer.confirm('确定要删除吗?', { icon: 3, title: '提示' }, function (index) {
    //do something
    $.ajax({
      type: 'DELETE',
      url: `/admin/links/${id}`,
      success: function (res) {
        // console.log(res);//{status: 0, message: "删除链接成功"}
        let { status, message } = res
        if (status === 0) {
          layer.msg(message);
          loadLinksInfo()
          layer.close(index);
        }
      }
    })
  });
});



//-----------------------------编辑连接-------------------
let form = layui.form;
let editLink;
$('tbody').on('click', '.edit', function (e) {
  //获取表单数据
  let id = $(e.target).data('id')
  $.ajax({
    url: `/admin/links/${id}`,
    success: function (res) {
      // console.log(res);
      /*
      data: {id: 7, linkname: "星球日报", linkurl: "https://www.odaily.com/", linkicon: "dailyPlanet.png", linkdesc: "星球日报", …}
      message: "获取链接成功"
      status: 0 */
      editLink = layer.open({
        type: 1,
        title: '编辑友情链接',
        content: $('#tpl-edit').html(),
        area: ['500px', '400px']
      });
      //设置图片预览
      $('#preIcon').attr('src', `http://localhost:8888/uploads/${res.data.linkicon}`)
      // 初始化表单数据
      delete res.data.linkicon//初始预览没有图片
      form.val('editForm', res.data)

      //绑定文件上传按钮点击事件（绑定两个按钮）点击button按钮绑定文件域点击
      $('#urlIcon').on('click', function () {
        $('#linkFile').click()
      })
      //监听file文件上传事件
      let file = null;
      $('#linkFile').on('change', function (e) {
        const url = URL.createObjectURL(e.target.files[0]);
        //  console.log(url);//blob:http://127260c
        file = e.target.files[0]
        $('#preIcon').attr('src', url)
      })

      //绑定表单提交事件
      $('#edit-form').on('submit', function (e) {
        e.preventDefault();
        let fd = new FormData(this)
        if (file) {
          fd.append('linkicon', file)
        }
        $.ajax({
          type: 'put',
          url: `/admin/links/${id}`,
          data: fd,
          processData: false,
          contentType: false,
          success: function (res) {
            let { status, message } = res
            if (status === 0) {
              layer.close(editLink)
              loadLinksInfo()
            }
          }
        })
      })
    }
  })


})







//-----------------------------添加连接-------------------
let addLink;
$('.add-link').on('click', function () {
  addLink = layer.open({
    type: 1,
    title: '添加友情链接',
    content: $('#tpl-add').html(),
    area: ['500px', '350px']
  });

  //---------------------------------------------------------------
  //绑定文件上传按钮点击事件（绑定两个按钮）点击button按钮绑定文件域点击
  $('#urlIcon').on('click', function () {
    $('#linkFile').trigger('click')
  })
  //监听file文件上传事件
  $('#linkFile').on('change', function (e) {
    const url = URL.createObjectURL(e.target.files[0]);
    //  console.log(url);//blob:http://127260c
    file = e.target.files[0]
    $('#preIcon').attr('src', url)
  })
  //-------------------------------------------------------
  //表单提交
  $('#add-form').on('submit', function (e) {
    e.preventDefault();
    let fd = new FormData(this);
      // console.log(fd);
    $.ajax({
      type: 'POST',
      url: '/admin/links',
      data: fd,
      processData: false,
      contentType: false,
      success: function (res) {
        console.log(res);
        if (res.status === 0) {
          layer.close(addLink)
          loadLinksInfo()
        }
      }
    })
  })
})

